package com.zxy.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zxy.reggie.common.R;
import com.zxy.reggie.entity.User;
import com.zxy.reggie.service.UserService;
import com.zxy.reggie.utils.SMSUtils;
import com.zxy.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author 周向阳
 * @Auther zik~
 * @Date 2022/9/11
 * @Description
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 验证码
     * @param user 用户
     * @param session session
     * @return R
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
//        获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            //        生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //        调用阿里云提供的短信服务发送短信 此处调用短信-服务测试版
//            SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
            //        储存返回的验证码到session
            log.info("生成的验证码是：{}",code);
            session.setAttribute(phone,code);
            return R.success("短信发送成功");
        }else {
            return R.error("短信发送失败");
        }
    }

    /**
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());
//       获取手机号
        Map map1 = (Map) map.get("phone");
        String phone = map1.get("phone").toString();
//       获取验证码
        String code = map1.get("code").toString();
//       与session中的验证码比对
        Object codeInSession = session.getAttribute(phone);
        if (codeInSession != null && codeInSession.equals(code)){
            //       判断
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);
            if (user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登录失败");
        }

}
